package com.example.mainproject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import lib.Consts;
import lib.ProcessFunc;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import classes.CookieData;

import android.os.AsyncTask;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.sax.RootElement;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TicketDetailsFragment extends Fragment {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";
	private Context context;
	private int TicketID;
	private String res ="";
	private View rootView;

	Button btnDeparture, btnArrive, btnProcess, btnFinish, btnReturn;
	TextView tvTicketNo, tvType, tvSerialno, tvAddress, tvDesc, tvDetail,
			tvContract, tvPhone, tvRequest, tvAssign, tvDeparture, tvArrive,
			tvProcess, tvFinish, tvReturn;
	

	public TicketDetailsFragment(Context context, int TicketID) {
		this.context = context;
		this.TicketID = TicketID;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LinearLayout wrapper = new LinearLayout(getActivity());
		rootView = inflater.from(context).inflate(
				R.layout.activity_ticket_details_fragment, wrapper, true);
		btnDeparture = (Button) rootView.findViewById(R.id.btnDeparture);
		btnArrive = (Button) rootView.findViewById(R.id.btnArrive);
		btnProcess = (Button) rootView.findViewById(R.id.btnProcess);
		btnFinish = (Button) rootView.findViewById(R.id.btnFinish);
		btnReturn = (Button) rootView.findViewById(R.id.btnReturn);
		
		tvTicketNo = (TextView) rootView.findViewById(R.id.Ticket_detail_tvTicketNo);
		tvType = (TextView) rootView.findViewById(R.id.Ticket_detail_tvType);
		tvSerialno = (TextView) rootView.findViewById(R.id.Ticket_detail_tvSerialNo);
		tvAddress = (TextView) rootView.findViewById(R.id.Ticket_detail_tvAddress);
		tvDesc = (TextView) rootView.findViewById(R.id.Ticket_detail_tvDesc);
		tvDetail = (TextView) rootView.findViewById(R.id.Ticket_detail_tvDetails);
		tvContract = (TextView) rootView.findViewById(R.id.Ticket_detail_tvContract);
		tvPhone = (TextView) rootView.findViewById(R.id.Ticket_detail_tvPhone);
//		tvTicketNo = (TextView) rootView.findViewById(R.id.Ticket_detail_tvre );
		tvAssign = (TextView) rootView.findViewById(R.id.Ticket_detail_tvAssign);
		tvDeparture = (TextView) rootView.findViewById(R.id.Ticket_detail_tvDeparture);
		tvArrive = (TextView) rootView.findViewById(R.id.Ticket_detail_tvArrive);
		tvProcess = (TextView) rootView.findViewById(R.id.Ticket_detail_tvProcess);
		tvFinish = (TextView) rootView.findViewById(R.id.Ticket_detail_tvFinish);
		tvReturn = (TextView) rootView.findViewById(R.id.Ticket_detail_tvReturn);
		tvRequest = (TextView) rootView.findViewById(R.id.Ticket_detail_tvRequest);
		
		myAsynctask myWebFetch = new myAsynctask();
        myWebFetch.execute();
		
		
		
		return rootView;
	}
	
	private class myAsynctask extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... arg0) {
			try {
		        res = GetTicket();
		    } 
			catch (Exception e) {
				e.printStackTrace();
			}
			return res;

		}
		@Override
		protected void onPostExecute(String result) {
			Log.d("test", result);
			if (result == "")
			{
				Toast.makeText(context, "System error!", Toast.LENGTH_SHORT).show();
				return;
			}
			String sResponse[] = result.split("\\|");
			if (Integer.parseInt(sResponse[0]) != 0)
			{
				Toast.makeText(context, sResponse[1], Toast.LENGTH_SHORT).show();
				return;
			}
			JSONArray jArray;
			try {
				jArray = new JSONArray(sResponse[1]);
				JSONObject json_data = jArray.getJSONObject(0);
				tvTicketNo.setText(json_data.getString(Consts.SDB_TICKETCODE));
				tvType.setText(json_data.getString(Consts.SDB_TYPE));
				tvSerialno.setText(json_data.getString(Consts.SDB_SERIALNO));
				tvAddress.setText(json_data.getString(Consts.SDB_ADDRESS));
				tvDesc.setText(json_data.getString(Consts.SDB_DESCRIPTION));
				tvDetail.setText(json_data.getString(Consts.SDB_DETAIL));
				tvContract.setText(json_data.getString(Consts.SDB_NAME));
				tvPhone.setText(json_data.getString(Consts.SDB_PHONE));
				
				
				SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
				dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
				String formattedDate = dateFormat.format(new Date());
				
				String temp = json_data.getString(Consts.SDB_REQUEST).trim();
				if (temp.length() != 0)
					tvRequest.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
				temp = json_data.getString(Consts.SDB_ASSIGN).trim();
				if (temp.length() != 0)
					tvAssign.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));	
				temp = json_data.getString(Consts.SDB_DEPARTURE).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvDeparture.setText(formattedDate);
				}else{
					tvDeparture.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					Button btDeparture = (Button) rootView.findViewById(R.id.btnDeparture);
					btDeparture.setEnabled(false);
				}
				temp = json_data.getString(Consts.SDB_ARRIVE).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvArrive.setText(formattedDate);
				}
				else
				{
					tvArrive.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					btnArrive.setEnabled(false);
				}
				temp = json_data.getString(Consts.SDB_PROCESS).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvProcess.setText(formattedDate);
				}
				else
				{
					tvProcess.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					btnProcess.setEnabled(false);
				}
				
				temp = json_data.getString(Consts.SDB_FINISH).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvFinish.setText(formattedDate);
//					tvSubFinish.setText(formattedDate);
				}
				else
				{
					tvFinish.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
					btnFinish.setEnabled(false);
				}
			
				temp = json_data.getString(Consts.SDB_RETURN).trim();
				if (temp.length() == 0)
				{
					formattedDate = dateFormat.format(new Date());
					tvReturn.setText(formattedDate);
				}
				else
				{
					tvReturn.setText(dateFormat.format(ProcessFunc.stringToDate(temp, "ddMMyyyyHHmm")));
//					Button btReturn = (Button)findViewById(R.id.tdbtReturn);
					btnReturn.setEnabled(false);
				}
				
				
				
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
			super.onPostExecute(result);
		}
		
	}
	
	private String GetTicket() {
    	InputStream is = null;
    	String result = "";
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(Consts.MAIN_URL);
    		
    		CookieData cookie = ProcessFunc.getCookie(context);
    		
    		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
            nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_TICKETDETAIL));
            nameValuePair.add(new BasicNameValuePair(Consts.V_USERID,String.valueOf(cookie.getUserId())));
            nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE,cookie.getCookie()));
            nameValuePair.add(new BasicNameValuePair(Consts.V_TICKETID, TicketID+""));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}
    	catch(Exception e){
    		Log.e("log_tag", "Error in http connection "+e.toString());
    	}

        try{
        	//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
	    	StringBuilder sb = new StringBuilder();
	    	String line = null;
	    	while ((line = reader.readLine()) != null) {
	    		sb.append(line + "\n");
	    	}
	    	is.close();
	    	result = sb.toString();
        }
		catch(Exception e){
	    	Log.e("test", "Error converting result "+e.toString());
	    }
        return result;
    }

}
